package com.ndp.fb.scheduler.job.extractdata;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Sets;
import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.data.api.service.schedulerservice.extractdata.ExtractDataService;
import com.ndp.fb.data.api.service.schedulerservice.extractdata.ExtractStatsServiceAll;
import com.ndp.fb.rdb.api.EntrustAccountRdbService;
import com.ndp.fb.rdb.model.EntrustAccount;
import com.ndp.fb.scheduler.annotation.CronScheduled;
import com.ndp.fb.util.DateFormatUtil;
import com.ndp.fb.util.DateUtil;
import com.ndp.fb.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Created by infi.he on 2015/10/27.
 */
@Component
public class ExtractdataJob {

    private final Logger logger = LoggerFactory.getLogger(ExtractdataJob.class);
    @Reference
    ExtractStatsServiceAll extractStatsService;
    @Reference
    EntrustAccountRdbService entrustAccountRdbService;

    @Reference
    ExtractDataService extractDataService;
    @CronScheduled(cronkey = ConfigConst.SCHEDULE_EXTRACT_ADGROUP_STATS_CRON, enablekey = ConfigConst.SCHEDULE_EXTRACT_ADGROUP_STATS_ENABLE)
    public void adGroupExtractStats() {
        //调用批次
        String uuid = "extract_stats_" + UUID.get();
        logger.info("抽取adGroupStat数据开始");
        extractStatsService.doExtract(888L, uuid, 1);
    }

    /**
     * 从给定日期开始抽取adgroup stats 数据
     * @throws InterruptedException
     */
    @CronScheduled(cronkey = ConfigConst.SCHEDULE_EXTRACT_ADGROUPSTATS_SINCEDATE_CRON, enablekey = ConfigConst.SCHEDULE_EXTRACT_ADGROUPSTATS_SINCEDATE_ENABLE)
    public void adGroupExtractStatsSinceDate()  {
        logger.info("开始执行抽取统计数据补数据业务，开始日期:"+ConfigCentre.getString(ConfigConst.SCHEDULE_EXTRACT_ADGROUP_STATS_FROMDATE));
        String dateSinceTo = ConfigCentre.getString(ConfigConst.SCHEDULE_EXTRACT_ADGROUP_STATS_FROMDATE);
        dateSinceTo=dateSinceTo.replaceAll("，",",");
        dateSinceTo=dateSinceTo.replaceAll(";",",");

        String sinceStr = dateSinceTo.split(",")[0];
        String toStr = dateSinceTo.split(",")[1];
        Date dateSince = null;
        Date dateTo = null;
        try {
            dateSince = DateFormatUtil.parseDateLong10(sinceStr);
            dateTo= DateFormatUtil.parseDateLong10(toStr);
        } catch (Exception e) {
            logger.error("解析日期出错，请确认配置项是否正确：schedule.extract.adgroup.stats.fromdate（yyyy-MM-dd）",e);
        }
        long diffSince = DateUtil.dayDiff(new Date(), dateSince);
        Long sinceLong = diffSince;
        Integer offsetSince = sinceLong.intValue();

        long diffTo = DateUtil.dayDiff(new Date(), dateTo);
        Long toLong = diffTo;
        Integer offsetTo = toLong.intValue();
        String uuid = null;
        while (offsetTo>offsetSince) {
            if (uuid != null) {
                logger.info("开始抽取偏移量{}的统计数据。",offsetSince);
                Boolean batchAllComplete = extractStatsService.isBatchAllComplete(uuid,1);
                if (!batchAllComplete) {
                    //没有全部完成，等待10s
                    logger.info("偏移量{} 的批次{}正在执行，60s后重试。",offsetSince,uuid);
                    try {
                        Thread.sleep(60*1000);
                    }catch (Exception e){
                        logger.info("偏移量{} 的批次{}正在执行，60s后重试,等待失败！！！"+e.getMessage(),offsetSince,uuid);
                    }
                }else{
                    //全部完成，进行下一批
                    offsetSince++;
                    uuid = "extract_stats_" + UUID.get();
                    filloldData(offsetSince, uuid);
                }
            }else{
                uuid = "extract_stats_" + UUID.get();
                filloldData(offsetSince, uuid);
            }

        }
    }

    private void filloldData(Integer offset, String uuid) {
        logger.info("抽取adGroupStats数据开始.");
        extractStatsService.doExtractOffset(888L, uuid, 1,offset);
    }

    @CronScheduled(cronkey = ConfigConst.SCHEDULE_EXTRACT_DATA_ADGROUP_CRON, enablekey = ConfigConst.SCHEDULE_EXTRACT_DATA_ADGROUP_ENABLE)
    public void adgroupExtractDataNew() {
        try {
            List<EntrustAccount> allAdAccount = entrustAccountRdbService.findAllAdAccount();
            //调用批次
            String uuid = "extract_data_" + UUID.get();
            //同一个公司下面去重
            Set<Long> accountSet = Sets.newHashSet();

            for (EntrustAccount entrustAccount : allAdAccount) {
                accountSet.add(entrustAccount.getFbAccountId());
            }

            accountSet.add(0L); // 没有上传图片的用户
            accountSet.add(1L); // 没有使用的图片

            logger.info("抽取adGroup数据 , 一共需要抽取 >>> [" + accountSet.size() + "] 个accountSet");
            for (Long aLong : accountSet) {
                logger.info("抽取adGroup数据 , FbAccountId >>> " + aLong);
                extractDataService.extractDataAdgroupByAccount(aLong, uuid, accountSet.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("抽取adGroup数据异常2222", e);
        } finally {
            logger.info("抽取adGroup数据完成");
        }
    }

}
